package com.example.learnspringboot.controller;

import com.example.learnspringboot.common.Result;
import com.example.learnspringboot.entity.User;
import com.example.learnspringboot.service.UserService;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;

/**
 * 功能
 * 作者:文诚锋
 * 日期:2023/10/17 17:05
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
//    通过@Autowired去容器中拿到UserService
    UserService userService;

    /**
     * 新增用户信息
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.insertUser(user);
        } catch (Exception e) {
            if (e instanceof SQLException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 单个删除用户信息
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success();
    }

    //批量删除用户信息
    @DeleteMapping("/delete/batch")
    //这里要传入多个,所以要通过数组传入进来
    public Result batchDelete(@RequestBody List<Integer> ids){
        userService.batchDeleteUser(ids);
        return Result.success();
    }

//    查询全部用户信息
    @GetMapping("/searchAll")
    public Result searchAll(){
        List<User> userList = userService.searchAllUser();
        return Result.success(userList);
    }

//    单条件查询
//    根据ID来查询用户信息
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        User user = userService.selectById(id);
        return Result.success(user);
    }

}